package com.etop.BankCard;

import android.content.Context;
import android.graphics.Bitmap;
import android.telephony.TelephonyManager;

import com.etop.bank.utils.BankConfig;

import java.io.File;

/**
 * 注意：这个类的包名只能是  com.etop.BankCard
 * 因为这个类的native方法，与底层的函数名相关联。修改包名就会因为找不到方法造成页面闪退
 */
public class BankCardAPI {
	static {//加载so库
		System.loadLibrary("AndroidCard");
	}

	/**
	 * 当前开发包版本号(请勿修改)
	 */
	public  int VERSION_CODE = 20201027;

	//初始化识别核心
	private native int ScanStart(String szSysPath,String FilePath,String CommpanyName,int nProductType,int nAultType,TelephonyManager telephonyManager,Context context);
	//释放识别核心
	private native void ScanEnd();
	//设置识别区域
	public native void SetRegion(int left,int top,int right,int bottom);
	//基于NV21字节流识别银行卡
	public native int ScanStreamNV21(byte[] streamnv21, int cols, int raws, int []Line,char[] cardno, int []wrapdata);
	//基于NV21字节流识别银行卡
	public native int ScanStreamNV21Ex(byte[] streamnv21, int cols, int raws, int []Line,char[] cardno, int []wrapdata, int type);
	//导入图片银行卡识别(图像路径方式)
	public native int ScanImage(String ImagePath,char[] cardNo);
	//导入图片银行卡识别(bitmap方式)，Bitmap必须是RGBA_8888格式
	public native int ScanBitmapImage(Bitmap bitmap,char[] cardno);
	//获取授权截止日期
	public native String GetEndTime();

	private static BankCardAPI bankApi = null;
	private static boolean isInitKernal = false;
	//返回-10，说明vinApi的对象为空，调用初始化核心方法之前，先调用getVinInstance()获取对象
	private int nRet = -10;

	/**
	 * 先获取 BankCardAPI 的对象
	 */
	public static BankCardAPI getBankInstance() {
		synchronized (BankCardAPI.class) {
			if (bankApi == null) {
				bankApi = new BankCardAPI();
			}
		}
		return bankApi;
	}
	/**
	 * 外部调用初始化核心的方法
	 */
	public int initBankKernal(Context context) {
		if (!isInitKernal && bankApi != null) {
			// 适配api-29
			BankConfig.saveImagePath(context);
			String userIdPath = new File(context.getCacheDir(), BankConfig.licenseId).getAbsoluteFile().toString();
			TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			String[] useNameArr = BankConfig.licenseId.split("\\.");
			String ncFilePath = context.getFilesDir().getPath();
			nRet = bankApi.ScanStart(ncFilePath, userIdPath, useNameArr[0], 0x04, BankConfig.nAultType, telephonyManager, context);
			if (nRet==0) isInitKernal = true;
		} else if (isInitKernal && bankApi != null) {
			return 0;
		}
		return nRet;
	}

	/**
	 * 外部调用释放识别核心的方法
	 */
	public void releaseKernal() {
		if (bankApi != null) {
			bankApi.ScanEnd();
			bankApi = null;
			isInitKernal = false;
		}
	}
}
